#!/bin/bash
# linux 下交叉编译 thmar(esp32)
# 基于conan 安装依赖库,并编译安装到本地目录
# author guyadong
# date 2024/08/28
#字符串转大写
#参数1：字符串
function string_toupper()
{
    echo $1 | tr '[a-z]' '[A-Z]'
}
#字符串转小写
#参数1：字符串
function string_lower()
{
    echo $1 | tr '[A-Z]' '[a-z]'
}

sh_folder=$(cd "$(dirname $0)"; pwd -P)

# 定义编译的目标平台(esp32)
CC=xtensa-esp32-elf-gcc
[ -n "$CROSS_COMPILER_PREFIX" ] && CC=$CROSS_COMPILER_PREFIX/bin/$CC

[ ! $($CC -dumpmachine) ] \
    && echo "not install compiler xtensa-esp32-elf-gcc,install please" \
    && exit 255

if ! which cmake 2>/dev/null 
then
    echo cmake NOT FOUND. && exit 255 
fi
if ! which conan 2>/dev/null 
then 
    echo conan NOT FOUND. && exit 255
fi
if  ! python --version 2>/dev/null | grep "Python 3." 
then
    echo Python 3 required. && exit 255
fi

machine=xtensa-esp32-elf
# 定义编译的版本类型(debug|release)
build_type=Release
[[ "$(string_lower $BUILD_TYPE)" =~ debug|release ]] && build_type=$(string_lower ${BUILD_TYPE})
prj_folder=$sh_folder/build/$machine

echo build_type=$build_type

# 安装路径, 默认安装到脚本所在目录的 release 目录下
# 如果指定了 PREFIX 环境变量, 则安装到该目录下
install_prefix=$sh_folder/release/thmar-$machine
[ -n "$PREFIX" ] && install_prefix="$PREFIX"

# 生成项目工程文件
[ -d $prj_folder ] && rm -fr $prj_folder
mkdir -p $prj_folder || exit 
pushd $prj_folder || exit
#  conan 安装依赖库到$prj_folder目录下
conan install "$sh_folder" -pr:h $sh_folder/conan2/profiles/esp32_gcc -pr:b default \
	-of $prj_folder \
	-s build_type=${build_type^} \
	-o with_paho=False -o build_test=False \
	--build missing || exit
#  -pr:h esp32_gcc 指定目标平台的profile
#  -pr:b default  指定编译平台的profile
#  --build missing 编译缺少的依赖库
echo "creating Project for $machine ..."
cmake "$sh_folder" -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=$build_type \
	-DCMAKE_TOOLCHAIN_FILE=$prj_folder/conan_toolchain.cmake \
	-DCMAKE_INSTALL_PREFIX=$install_prefix \
	-DCMAKE_SH="CMAKE_SH-NOTFOUND" -DCMAKE_POLICY_DEFAULT_CMP0091="NEW" || exit

echo "building Project for $machine ..."
cmake --build . --config $build_type --target install -- -j 8 || exit 

popd || exit


